package com.jiedeng.controller.index;

import com.google.code.kaptcha.Producer;
import com.jiedeng.util.ForwardConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * 公共方法类
 *
 * @author zhouyb
 */
@Controller
@RequestMapping("/common/")
public class CommonController {
    private final Logger logger = LoggerFactory.getLogger(CommonController.class);
    @Value("${config.prefix}")
    public String downUrl;
    @Autowired
    private Producer captchaProducer;

    /**
     * 获取验证码
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("kaptcha")
    public ModelAndView getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        // String code = (String) session.getAttribute("validateCode");
        // System.out.println("******************验证码是: " + code +
        // "******************");

        response.setDateHeader("Expires", 0);

        // Set standard HTTP/1.1 no-cache headers.
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

        // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");

        // Set standard HTTP/1.0 no-cache header.
        response.setHeader("Pragma", "no-cache");

        // return a jpeg
        response.setContentType("image/jpeg");

        // create the text for the image
        String capText = captchaProducer.createText().toLowerCase();

        // store the text in the session
        session.setAttribute("validateCode", capText);

        // create the image with the text
        BufferedImage bi = captchaProducer.createImage(capText);
        logger.info("CommonController getKaptchaImage response.getOutputStream() start");
        ServletOutputStream out = response.getOutputStream();
        logger.info("CommonController getKaptchaImage response.getOutputStream() end");
        // write the data out
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }
        return null;
    }

    /**
     * 封装公共的文件下载方法，
     *
     * @param path     文件的绝对路径，包括文件名
     * @param type     类型，0跟null为加密，其它为URL不用URLENCODER 加密
     * @param response 返回体
     * @return
     */
    @RequestMapping("downloadfile")
    public void download(String path, String type, HttpServletResponse response, HttpServletRequest request) {
        OutputStream toClient = null;
        InputStream fis = null;
        try {
            response.setCharacterEncoding(ForwardConstants.UTF8);
            String filePath;
            if (type == null || "0".equals(type)) {
                filePath = URLDecoder.decode(path, ForwardConstants.UTF8);
            } else {
                filePath = path;
            }
            // path是指欲下载的文件的路径。
            File file = new File(filePath);
            // 取得文件名。
            // String filename = URLEncoder.encode(file.getName(),
            // AttrConstants.UTF8);
            String fileName = file.getName();
            fis = new BufferedInputStream(new FileInputStream(filePath));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            String header = request.getHeader("User-Agent").toUpperCase();
            if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
                fileName = URLEncoder.encode(fileName, "utf-8");
                fileName = fileName.replace("+", "%20"); // IE下载文件名空格变+号问题
            } else {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            }
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName); // new
            // String(filename.getBytes(),
            // AttrConstants.UTF8)
            response.addHeader("Content-Length", "" + file.length());
            logger.info("CommonController download response.getOutputStream() start");
            toClient = new BufferedOutputStream(response.getOutputStream());
            logger.info("CommonController download response.getOutputStream() end");
//            toClient.write(buffer);
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (toClient != null) {
                    toClient.flush();
                    toClient.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
